import { APP_INITIALIZER } from '@angular/core';
import { first } from 'rxjs';

import { NzMessageService } from 'ng-zorro-antd/message';

import { ThemeService, ThemeType } from './theme.service';
import { WindowService } from './window.service';

// 主题键值
const THEME_STORAGE_KEY = 'THEME-STORAGE-KEY';

export const ThemeAppInitializer = {
  provide: APP_INITIALIZER,
  useFactory: (themeSrc: ThemeService, windowSrc: WindowService, messageSrc: NzMessageService) => () => {
    // 主题修改事件
    themeSrc.onThemeTypeChanged.subscribe(theme => {
      themeSrc.changeTheme(theme).then(() => {
        windowSrc.setStorage(THEME_STORAGE_KEY, theme);
        messageSrc.success('主题加载成功');
      });
    });

    // 加载主题
    var theme = windowSrc.getStorage(THEME_STORAGE_KEY);
    if (theme == null) {
      theme = ThemeType.default;
    }
    return themeSrc.initTheme(theme);
  },
  deps: [ThemeService, WindowService, NzMessageService],
  multi: true
};
